<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/10
 * Time: 13:39
 */

namespace app\index\model\user;


use app\index\model\area\Area;
use basic\ModelBasic;
use think\Db;
use traits\ModelTrait;

class UserAddress extends ModelBasic
{
    use ModelTrait;
    public static function tableName()
    {
        return 'user_address';
    }

    public static function GetAddressList($user_id)
    {
        $address = Db::name(self::tableName())->where('user_id',$user_id)->select();
        foreach ($address as $key=>$value){
            $address[$key]['province_name'] = Area::GetAreaName($value['province'],'name');
            $address[$key]['city_name'] = Area::GetAreaName($value['city'],'name');
            $address[$key]['district_name'] = Area::GetAreaName($value['district'],'name');
        }
        return $address;
    }

    public static function UpIsDefault($id,$user_id){

        $up_address = false !== self::where('user_id', $user_id)->where('id','<>',$id)->update(['is_default'=>0]);
        $address = false !== self::where('id', $id)->update(['is_default'=>1]);
        if(!$address || !$up_address) return self::setErrorInfo('修改地址失败!');
        return true;
    }

    public static function AddIsDefault($user_id,$data=[],$id=0){
        $is_default = !empty($data['is_default']) ? $data['is_default'] : 0;
        $user_address = self::where('user_id',$user_id)->find();
        if(empty($user_address)){
            $is_default = 1;
        }elseif(!empty($user_address) && !empty($is_default)){
            $address = false !==  self::where('user_id', $user_id)->update(['is_default'=>0]);
            if(!$address) return self::setErrorInfo('修改地址失败!');
        }
        $district = $data['region_id'];
        $address =Area::GetAreaOne($district);
        $city = Area::GetAreaPid($district);
        $province = Area::GetAreaPid($city);
        $AddressInfo = [
            'user_id' =>$user_id,
            'real_name' =>$data['real_name'],
            'phone' =>$data['phone'],
            'province' =>$province,
            'city' =>$city,
            'district' =>$district,
            'detail' =>$data['detail'],
            'post_code' =>!empty($address['zip_code']) ? $address['zip_code'] : 0,
            'longitude' =>!empty($address['lng']) ? $address['lng'] : 0,
            'latitude' =>!empty($address['lat']) ? $address['lat'] : 0,
            'is_default' =>$is_default,
            'add_time' =>time(),
        ];
        if(empty($id)){
            $address = self::set($AddressInfo);
        }else{
            $address = self::edit($AddressInfo,$id,'id');
        }

        if(!$address)return self::setErrorInfo('地址添加/修改失败!');
        return true;
    }
}